#include <iostream>
#include <fcntl.h>
#include <cstring>
#include <unistd.h>

void setnonblock(int fd)
{
    int n = fcntl(fd, F_GETFD);
    if (n < 0)
    {
        perror("fcntl");
        exit(1);
    }
    if (fcntl(fd, F_SETFL,n | O_NONBLOCK) > 0)
    {
        std::cout << "fd : " << fd << "设置非阻塞成功" << std::endl;
    }
}

int main()
{
    setnonblock(0);
    char bufstr[1024];
    while (true)
    {
        int n = read(0, bufstr, sizeof(bufstr) - 1);
        if (n > 0)
        {
            bufstr[n] = 0;
            std::cout << bufstr << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "写端退出" << std::endl;
            exit(2);
        }
        else
        {
            sleep(1);
            // std::cout << "errno :" << errno << ",strerror" << strerror(errno) << std::endl;
            if(errno == EWOULDBLOCK)
            {
               std::cout << "正常进行任务" << std::endl; 
            }
            else
           {
                std::cout << "读取失败" << std::endl;
                //break;
            }
        }
    }

    return 0;
}
